<template>
  <page-view class="page-view" :title="false">
    <div slot="headerContent">
      <a-breadcrumb class="s-breadcrumb">
        <a-breadcrumb-item><nuxt-link to="/meal/manage">餐券管理</nuxt-link></a-breadcrumb-item>
        <a-breadcrumb-item><nuxt-link to="/meal/date">订餐日期设置</nuxt-link></a-breadcrumb-item>
        <a-breadcrumb-item>日期详情</a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <a-card class="s-card">
      <a-spin :spinning="sending">
        <div class="detail-item"><span>订餐日期：{{ dateStr }}</span></div>
        <div class="detail-item"><span>可订时间：</span>
          <div v-show="!isEdit">
            <span>{{ mealChecked.map(i => mealTypeMaps.get(i).name).join('、') || '无' }}</span>
          </div>
          <div v-show="isEdit">
            <a-checkbox-group
              :value="mealChecked"
              :options="mealType.concat().splice(1).map(({ name, id }) => ({ label: name, value: id }))"
              @change="onchange"
            />
          </div>
        </div>
        <div class="detail-item"><span>详细数据：</span> </div>
        <s-table
          class="s-table"
          bordered
          :columns="columns"
          :data="loadData"
          :show-pagination="false"
          :alert="false"
          row-key="name"
        />
        <div class="footer-btn">
          <div v-if="$moment(dateStr).isAfter($moment().add(2, 'day'))">
            <a-button v-show="!isEdit" type="primary" :loading="sending" @click="changeEdit">修改</a-button>
            <a-button v-show="isEdit" type="primary" :loading="sending" @click="handleEdit">确定</a-button>
          </div>
          <a-button @click="goback">取消</a-button>
        </div>
      </a-spin>
    </a-card>
  </page-view>
</template>
<script>
import { PageView, STable } from '@/components'
import { mapState, mapActions } from 'vuex'

export default {
  name: 'Detail',
  components: { PageView, STable },
  props: {
    dateStr: {
      type: String,
      default: ''
    }
  },

  validate ({ params }) { return !!params.dateStr },

  async asyncData ({ store, route }) {
    const data = {
      mealChecked: []
    }
    const { $moment, $get, getters } = store
    const { mealTypeNames, scheduleMaps } = getters.meal
    const { dateStr } = route.params
    const params = {}
    params.scheduleDate = $moment(dateStr || '').format('YYYY-MM-DD')
    if (!$get(mealTypeNames, 'length')) await store.dispatch('meal/getMealType')
    await store.dispatch('meal/getSchedule', params)
    data.mealChecked = $get(scheduleMaps, `${dateStr}.typeIds`, '').split(',').filter(i => i).map(i => i / 1)
    return data
  },

  data () {
    return {
      sending: false,

      columns: [
        { title: '订餐时间', align: 'center', dataIndex: 'name' },
        { title: '订餐总数(张)', align: 'center', dataIndex: 'totalQty' },
        { title: '已使用(张)', align: 'center', dataIndex: 'usedQty' },
        { title: '未使用(张)', align: 'center', dataIndex: 'unusedQty' },
        { title: '已过期(张)', align: 'center', dataIndex: 'expiredQty' },
        { title: '换餐数(张)', align: 'center', dataIndex: 'exchangeQty' }
      ],
      isEdit: false,
      mealChecked: [],

      loadData: () => {
        const { $axios, dateStr, $get, $notification } = this
        return $axios.post('api/mealCoupon/queryOverall', { pageNum: -1, scheduleDate: dateStr }).then(res => {
          return { data: $get(res, 'data.data.dataList', []) }
        }).catch(e => {
          $notification.error({ message: '连接服务器超时' })
        })
      }
    }
  },

  computed: {
    ...mapState({
      mealType: state => state.meal.mealType,
      mealTypeMaps: state => state.meal.mealTypeMaps,
      scheduleMaps: state => state.meal.scheduleMaps
    })
  },

  methods: {
    ...mapActions('meal', ['getSchedule']),

    onchange (arr) {
      const { mealChecked, $difference, scheduleMaps, $get, dateStr } = this
      if (arr.length < mealChecked.length) {
        const delId = $difference(mealChecked, arr)[0]
        const oldIds = $get(scheduleMaps, `${dateStr}.typeIds`, '')
        if (oldIds.includes(delId)) {
          this.$message.destroy()
          this.$message.error('请前往新建换餐通知处删除')
          return
        }
      }
      mealChecked.splice(0, mealChecked.length, ...arr.sort())
    },

    changeEdit () {
      this.isEdit = true
    },

    goback () {
      this.$router.go(-1)
    },

    async handleEdit () {
      if (this.sending) return false
      const { $axios, mealTypeMaps, scheduleMaps, dateStr, $get, $difference, mealChecked, getSchedule } = this
      this.$toggleSending(1)
      const oldIds = $get(scheduleMaps, `${dateStr}.typeIds`, '').split(',').map(i => i / 1)
      const addIds = $difference(mealChecked, oldIds).filter(i => i)
      const addForm = addIds.map(id => {
        const { price, endTime, startTime, name } = mealTypeMaps.get(id / 1)
        return { scheduleDate: dateStr, price, endTime, startTime, typeId: id, name }
      })
      if (addForm.length) {
        await $axios.post('api/mealSchedule/', addForm)
        await getSchedule({ scheduleDate: dateStr, refresh: false })
      }
      this.isEdit = false
      this.$toggleSending()
    }
  }
}
</script>

<style lang="less" scoped>
.s-card{
  .detail-item{
    .Flex;
    margin-bottom: 30px;
    span{
      font-weight: bold;
    }
    /deep/ .ant-checkbox-group-item{
      margin-left: 20px;
    }
  }
  .footer-btn{
    margin-top: 20px;
      .Flex;
      justify-content: center;
      .ant-btn{
          margin-right: 50px;
      }
  }
}

</style>
